<template>
  <div>
    <el-form :inline="true" :model="repairDto" label-width="110px" ref="searchForm">

      <el-form-item>
        <el-row>
          <el-select v-model="repairDto.provinceCode" clearable placeholder="请选择省份" @click="getAllProvince()"
                     v-if="repairDto.roleType == 1" @change="getAllCity()">
            <el-option
              v-for="item in allProvince"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <el-select v-model="repairDto.cityCode" clearable placeholder="请选择城市" @click="getAllCity()"
                     v-if="repairDto.roleType == 1 || (repairDto.roleType == 2 && repairDto.officeType == 0)"
                     prop="cityRule" @change="onCityChange()">
            <el-option
              v-for="item in allCity"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-row>
      </el-form-item>

      <!--网点类型查询-->
      <el-form-item v-if="repairDto.officeType === '0'">
        <el-select v-model="repairDto.pointType" placeholder="请选择网点类型" @change="onPointChange()">
          <el-option
            v-for="item1 in pointTypeOptions"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="repairDto.pointType === 0">
        <el-select v-model="repairDto.pointId" placeholder="请选择办事处" clearable>
          <el-option
            v-for="item1 in pointOptions"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="repairDto.pointType === 1 ">
        <el-select v-model="repairDto.pointId" placeholder="请选择外包商" clearable>
          <el-option
            v-for="item1 in outsourceOptions"
            :key="item1.id"
            :label="item1.company"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="repairTime">
        <el-date-picker
          v-model="repairDto.repairTime"
          type="daterange"
          range-separator="至"
          start-placeholder="维修开始时间"
          end-placeholder="维修结束时间"
          value-format="yyyy-MM-dd"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="repairDto.repairSite===1" prop="backTime">
        <el-date-picker
          v-model="repairDto.backTime"
          type="date"
          placeholder="返还网点时间"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="repairDto.repairSite===1" prop="endYMD">
        <el-date-picker
          v-model="repairDto.endYMD"
          type="date"
          placeholder="返厂时间"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="repairDto.repairSite===2" prop="startYMD">
        <el-date-picker
          v-model="repairDto.startYMD"
          type="date"
          placeholder="返还客户时间"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="repairDto.repairSite===2">
        <el-date-picker
          v-model="repairDto.acceptTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="受理开始日期"
          end-placeholder="受理结束日期"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="ystsn">
        <el-input v-model="repairDto.ystsn" placeholder="ystsn号"></el-input>
      </el-form-item>
      <el-form-item prop="repairType" v-if="false">
        <el-select v-model="repairDto.repairType" placeholder="维修单位">
          <el-option :key="3" label="市级维修网点维修记录" value="市级维修网点维修记录"></el-option>
          <el-option :key="2" label="省级维修网点维修记录" value="省级维修网点维修记录"></el-option>
          <el-option :key="1" label="工厂维修记录" value="工厂维修记录"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="repairDto.repairType" placeholder="维修单位" @change="changeType(repairDto.repairType)">
          <el-option :key="2" label="维修网点维修记录" value="维修网点维修记录"></el-option>
          <el-option :key="1" label="工厂维修记录" value="工厂维修记录"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="repairResult">
        <el-select v-model="repairDto.repairResult" clearable placeholder="维修结果">
          <el-option
            v-for="item in resultChart"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchDate()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="exportLoading" @click="excelExport()">数据导出</el-button>
      </el-form-item>
      <el-form-item v-if="repairDto.repairSite === 2">
        <el-tooltip placement="top-start" effect="light">
          <span slot="content">全流程维修数据导出所需时间较长，请耐心等待。<br/>建议一次导出不超过3个月的数据！<br/>并且筛选条件只支持省、市、网点、接收日期、维修日期及sn号！</span>
          <el-button :loading="wholeProcessLoading" type="primary" @click="wholeProcessExport()">全流程维修数据导出</el-button>
        </el-tooltip>
      </el-form-item>
    </el-form>


    <!-- 维修网点维修记录-->
    <div v-show="columnShowFlag === '维修网点'">
      <custom-table
        :columns="pointColumns"
        :data="repairList"
        :tableLoadingFlag="tableLoadingFlag"
        :pagination="pagination">
      </custom-table>
    </div>
    <!--工厂维修记录-->
    <div v-show="columnShowFlag === '工厂'">
      <custom-table
        :columns="factoryColumns"
        :data="repairList"
        :tableLoadingFlag="tableLoadingFlag"
        :pagination="pagination">
      </custom-table>
    </div>
  </div>

</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {
    apiGetRepairList
    , apiPointRepairRecordExport
    , apiFactoryRepairRecordExport
  } from '@/api/search/dictionary'
  import {parseTime} from '@/utils'
  import {
    getUserId,
    getRoleType,
    getOfficeType,
    getOfficeProvinceCode,
    getOutsourceProvinceCode,
    getProvinceCode,
    getOutsourceType,
    getCityCode
  } from '@/utils/token'
  import {
    apiGetCity, apiGetMaterielList, apiGetAllPointOffice
  } from '@/api/dictionary'
  import {apiGetOutsourcerList} from '@/api/basic/info/outsourcer'
  import {apiGetOfficeList} from '@/api/basic/info/inside/office'
  import {downloadExcel} from "../../utils";
  import {apiWholeProcessExcel} from '@/api/excel/excelWrite'
  // import {getCityCode, getOutsourceCityCode} from "../../utils/token";

  export default {
    components: {
      CustomTable
    },
    created () {
      // let listQuery = {
      //   repairSite: 2,
      //   pageNumber: this.pagination.currentPage,
      //   pageSize: this.pagination.pageSize
      // }
      if (getRoleType() === '3') {
        this.repairDto.provinceCode = getOutsourceProvinceCode()
        if (getOutsourceType() === '0') {
          this.repairDto.cityCode = getCityCode()
        }
      }
      if (getRoleType() === '2') {
        this.repairDto.provinceCode = getOfficeProvinceCode()
        this.repairDto.officeType = getOfficeType()
        if (getOfficeType() === '1') {
          this.repairDto.cityCode = getCityCode()
        }
        console.log(this.repairDto.cityCode)
      }
      this.columnShowFlag = '维修网点'
//      this.getRepairList(listQuery)
      this.getAllProvince()
      this.getAllCity()
      this.getMaterialList()
      this.getOffice()
    },
    data () {
      return {
        tableLoadingFlag: false,
        repairDto: {
          repairType: '维修网点维修记录',
          repairSite: 2,
          repairResult: '',
          provinceCode: '',
          cityCode: '',
          startYMD: '',
          endYMD: '',
          ystsn: '',
          repairTime: '',
          backTime: '',
          acceptTime: '',
          roleType: getRoleType(),
          officeType: '',
          pointType: '', // 网点类型
          pointId: '' // 办事处or外包商id
        },
        // 网点类型选择
        pointTypeOptions: [
          {
            'id': 0,
            'name': '办事处'
          },
          {
            'id': 1,
            'name': '外包商'
          }
        ],
        // 办事处一览
        pointOptions: [],
        // 外包商一览
        outsourceOptions: [],
        pointIdArray: [],
        pointColumns: [
          {label: '受理时间', name: 'acceptedTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '客户所在省份', name: 'province', width: '100', align: 'center'},
          {label: '客户所在地市', name: 'city', width: '100', align: 'center'},
          {label: '客户类型', name: 'customerType', width: '100', align: 'center'},
          {label: '客户姓名', name: 'customerName', width: '100', align: 'center'},
          {label: '联系电话', name: 'tel', width: '100', align: 'center'},
          {label: '品牌', name: 'brandName', width: '100', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '100', align: 'center'},
          {label: 'STBID', name: 'stbId', width: '100', align: 'center'},
          {label: '型号', name: 'modelName', width: '100', align: 'center'},
          {label: '备机YSN', name: 'newYstsn', width: '100', align: 'center'},
          {label: '备机型号', name: 'newModelName', width: '100', align: 'center'},
          {label: '生产厂商', name: 'factoryName', width: '100', align: 'center'},
          {label: '维修时间', name: 'repairTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '返还客户时间', name: 'backToCustomerTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '包修截止日期', name: 'expirationDate', width: '160', align: 'center', formatter: this.formatTime},
          {label: '服务类型', name: 'serviceType', width: '100', align: 'center'},
          {label: '故障分类', name: 'faultType', width: '100', align: 'center'},
          {label: '故障现象', name: 'faultAppearance', width: '100', align: 'center'},
          {label: '是否用料', name: 'isMaterial', width: '100', align: 'center'},
          {label: '故障处理', name: 'faultTreatment', width: '100', align: 'center'},
          {label: '接收物流单号', name: 'acceptLogisticsNumber', width: '100', align: 'center'},
          {label: '返还物流单号', name: 'returnCustomerNumber', width: '100', align: 'center'},
          {label: '维修结果', name: 'repairResult', width: '100', align: 'center'}
        ],
        factoryColumns: [
          {label: '品牌', name: 'brandName', width: '100', align: 'center'},
          {label: '维修工厂', name: 'factoryName', width: '100', align: 'center'},
          {label: '返厂批次号', name: 'batch', width: '100', align: 'center'},
          {label: '返厂时间', name: 'backTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '返还时间', name: 'returnTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '维修时间', name: 'repairTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '网点收机时间', name: 'pointReceiveTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '省份', name: 'province', width: '100', align: 'center'},
          {label: '地市', name: 'city', width: '100', align: 'center'},
          {label: '型号', name: 'modelName', width: '100', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '100', align: 'center'},
          {label: '责任归属', name: 'duty', width: '100', align: 'center'},
          {label: '故障分类', name: 'faultType', width: '100', align: 'center'},
          {label: '故障现象', name: 'faultAppearance', width: '100', align: 'center'},
          {label: '是否用料', name: 'isMaterial', width: '100', align: 'center'},
          {label: '用料明细', name: 'replaceParts', width: '100', align: 'center'},
          {label: '故障处理', name: 'faultTreatment', width: '100', align: 'center'},
          {label: '返厂物流单号', name: 'backFactoryNumber', width: '100', align: 'center'},
          {label: '返网点物流单号', name: 'backPointNumber', width: '100', align: 'center'},
          {label: '维修结果', name: 'repairResult', width: '100', align: 'center'}
        ],
        repairList: [],
        pagination: this.getData(this.getRepairList),
        resultChart: [
          {value: 1, label: '待修复'},
          {value: 2, label: '已修复'},
          {value: 3, label: '原物返回'},
          {value: 4, label: '待报废'},
          {value: 5, label: '已报废'},
          {value: 6, label: '报废未批准'}
        ],
        repairSiteChart: [
          {value: 1, label: '工厂维修记录'},
          {value: 2, label: '省级网点维修记录'},
          {value: 3, label: '市级网点维修记录'}
        ],
        listQuery: {
          provinceCode: undefined,
          cityCode: undefined,
          startYMD: undefined,
          endYMD: undefined,
          repairSite: undefined,
          repairResult: undefined,
          ystsn: undefined,
          repairTime: undefined,
          backTime: undefined,
          acceptTime: undefined,
          beginTime: undefined,
          endTime: undefined,
          //  维修开始，结束时间
          startTime: undefined,
          overTime: undefined,
          pointType: undefined,
          pointId: undefined,
          officeType: ''
        },
        columnShowFlag: '维修网点',
        allProvince: [],
        allCity: [],
        materialList: [],
        exportData: [],
        fileName: '',
        exportLoading: false,
        wholeProcessLoading: false
      }
    },
    methods: {
      excelExport () {
        this.exportLoading = true
        let paramsPost = {
          provinceCode: this.repairDto.provinceCode,
          cityCode: this.repairDto.cityCode,
          repairSite: this.repairDto.repairSite,
          startYMD: this.repairDto.startYMD,
          endYMD: this.repairDto.endYMD,
          repairResult: this.repairDto.repairResult,
          ystsn: this.repairDto.ystsn,
          userId: getUserId(),
          backTime: this.repairDto.backTime,
          startTime: this.repairDto.repairTime[0],
          overTime: this.repairDto.repairTime[1],
          beginTime: this.repairDto.acceptTime[0],
          endTime: this.repairDto.acceptTime[1],
          pointId: this.repairDto.pointId,
          pointType: this.repairDto.pointType,
          officeType: this.repairDto.officeType
        }
        if (paramsPost.repairSite === 1) {
          apiFactoryRepairRecordExport(paramsPost).then(response => {
            this.exportLoading = false
            downloadExcel(response.data, '自有售后工厂维修记录信息导出表')
          }).catch(() => {
            this.exportLoading = false
          })
        } else if (paramsPost.repairSite === 2) {
          apiPointRepairRecordExport(paramsPost).then(response => {
            this.exportLoading = false
            downloadExcel(response.data, '自有售后网点维修记录信息导出表')
          }).catch(() => {
            this.exportLoading = false
          })
        }
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      getRepairList (listQuery) {
        this.tableLoadingFlag = true
        if (isNaN(listQuery.repairSite)) {
          listQuery.repairSite = this.repairDto.repairSite
        }
        if (listQuery.provinceCode === undefined) {
          listQuery.provinceCode = this.repairDto.provinceCode
        }
        if (listQuery.cityCode === undefined) {
          listQuery.cityCode = this.repairDto.cityCode
        }
        if (listQuery.repairSite === 1 && listQuery.endYMD === undefined) {
          listQuery.endYMD = this.repairDto.endYMD
        }
        if (listQuery.repairSite === 2 && listQuery.startYMD === undefined) {
          listQuery.startYMD = this.repairDto.startYMD
        }
        if (listQuery.repairResult === undefined) {
          listQuery.repairResult = this.repairDto.repairResult
        }
        if (listQuery.ystsn === undefined) {
          listQuery.ystsn = this.repairDto.ystsn
        }
        if (listQuery.repairTime === undefined) {
          listQuery.repairTime = this.repairDto.repairTime
        }
        if (listQuery.startTime === undefined) {
          listQuery.startTime = this.listQuery.startTime
        }
        if (listQuery.overTime === undefined) {
          listQuery.overTime = this.listQuery.overTime
        }
        if (listQuery.beginTime === undefined) {
          listQuery.beginTime = this.repairDto.acceptTime[0]
        }
        if (listQuery.endTime === undefined) {
          listQuery.endTime = this.repairDto.acceptTime[1]
        }
        if (!listQuery.pointType) {
          listQuery.pointType = this.repairDto.pointType
        }
        if (!listQuery.pointId) {
          listQuery.pointId = this.repairDto.pointId
        }
        if (!listQuery.officeType) {
          listQuery.officeType = this.repairDto.officeType
        }
        apiGetRepairList(listQuery).then(response => {
          this.repairList = response.data
          this.pagination.totalRecords = response.totalRecords
          if (this.repairDto.repairSite === 2) {
            this.columnShowFlag = '维修网点'
          } else {
            this.columnShowFlag = '工厂'
          }
          for (let i in this.repairList) {
            if (this.repairList[i].isMaterial === 0) {
              this.repairList[i].isMaterial = '是'
            } else if (this.repairList[i].isMaterial === 1) {
              this.repairList[i].isMaterial = '否'
            } else {
              this.repairList[i].isMaterial = ' '
            }
          }
          for (let i in this.repairList) {
            if (this.repairList[i].serviceType === 0) {
              this.repairList[i].serviceType = '保内'
            } else if (this.repairList[i].serviceType === 1) {
              this.repairList[i].serviceType = '保外'
            } else {
              this.repairList[i].serviceType = ''
            }
          }
          for (let i in this.repairList) {
            var rpStr = '{'
            if (this.repairList[i].replaceParts === '{}') {
            } else {
              let rs = this.repairList[i].replaceParts
              rs = rs.substring(1, rs.length - 1).split(',')
              for (let j in rs) {
                let part = rs[j].split(':')
                let material = part[0].trim().substring(1, 2)
                let num = part[1].trim().substring(1, 2)
                for (let m in this.materialList) {
                  if (parseInt(material) === this.materialList[m].id) {
                    material = this.materialList[m].name
                  }
                }
                rpStr = rpStr + material + ': ' + num + ', '
              }
            }
            if (rpStr.length > 2) {
              rpStr = rpStr.substring(0, rpStr.length - 2) + '}'
            } else {
              rpStr = ''
            }
            this.repairList[i].replaceParts = rpStr
          }
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      searchDate () {
        this.listQuery.pointType = this.repairDto.pointType
        this.listQuery.pointId = this.repairDto.pointId
        this.listQuery.officeType = this.repairDto.officeType
        this.listQuery.repairSite = this.repairDto.repairSite
        this.listQuery.provinceCode = this.repairDto.provinceCode
        this.listQuery.cityCode = this.repairDto.cityCode
        this.listQuery.ystsn = this.repairDto.ystsn
        this.listQuery.repairResult = this.repairDto.repairResult
        this.listQuery.startTime = this.repairDto.repairTime === null ? '' : this.repairDto.repairTime[0]
        this.listQuery.overTime = this.repairDto.repairTime === null ? '' : this.repairDto.repairTime[1]
        if (this.repairDto.repairSite === 1) {
          this.listQuery.endYMD = this.repairDto.endYMD
          this.listQuery.backTime = this.repairDto.backTime
        }
        if (this.repairDto.repairSite === 2) {
          this.listQuery.startYMD = this.repairDto.startYMD
          if (this.repairDto.acceptTime !== null) {
            this.listQuery.beginTime = this.repairDto.acceptTime[0]
            this.listQuery.endTime = this.repairDto.acceptTime[1]
          }
        }
        if (this.repairDto.acceptTime === null) {
          this.listQuery.beginTime = ''
          this.listQuery.endTime = ''
        }
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getRepairList(this.listQuery)
      },
      formatTime (row, column, cellValue) {
        if (column.label === '包修截止日期') {
          return parseTime(cellValue, '{y}-{m}-{d}')
        } else if (column.property === undefined) {
          return
        } else {
          return parseTime(cellValue)
        }
      },
      changeType (value) {
        if (value === '维修网点维修记录') {
          this.repairDto.repairSite = 2
        } else {
          this.repairDto.repairSite = 1
        }
      },
      getAllCity () {
        this.repairDto.cityCode = ''
        if (this.repairDto.provinceCode === '') {
          this.allCity = []
        } else {
          let listQuery = {
            province: this.repairDto.provinceCode
          }
          apiGetCity(listQuery).then(response => {
            this.allCity = response.data
          })
        }
      },
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      },
      getMaterialList () {
        apiGetMaterielList().then(rsp => {
          this.materialList = rsp.data
        })
      },
      onPointChange () {
        if (this.repairDto.pointType === 0) {
          let listQuery = {
            province: this.repairDto.provinceCode,
            city: this.repairDto.cityCode
          }
          this.getOfficeByCity(listQuery)
        } else {
          let listQuery = {
            provinceCode: this.repairDto.provinceCode,
            cityCode: this.repairDto.cityCode
          }
          this.outsourceOptions = []
          this.getOutsourceByCity(listQuery)
        }
      },
      onCityChange () {
        if (this.repairDto.pointType === 0) {
          let listQuery = {
            province: this.repairDto.provinceCode,
            city: this.repairDto.cityCode
          }
          this.pointOptions = []
          this.getOfficeByCity(listQuery)
        } else {
          let listQuery = {
            provinceCode: this.repairDto.provinceCode,
            cityCode: this.repairDto.cityCode
          }
          this.outsourceOptions = []
          this.getOutsourceByCity(listQuery)
        }
      },
      // 获取网点一览
      getOffice () {
        let listQuery = {
          provinceCode: this.repairDto.provinceCode,
          pageNumber: 1,
          pageSize: 100
        }
        apiGetOfficeList(listQuery).then(response => {
          this.pointOptions = response.data
        })
      },
      // 获取外包商一览
      getOutsource () {
        let listQuery = {
          provinceCode: this.repairDto.provinceCode,
          pageNumber: 1,
          pageSize: 100
        }
        apiGetOutsourcerList(listQuery).then(response => {
          this.outsourceOptions = response.data
        })
      },
      // 按地区条件获取网点
      getOfficeByCity (listQuery) {
        this.repairDto.pointId = ''
        apiGetAllPointOffice(listQuery).then(response => {
          this.pointOptions = response.data
        })
      },
      // 按地区获取外包商
      getOutsourceByCity (listQuery) {
        this.repairDto.pointId = ''
        listQuery.pageNumber = 1
        listQuery.pageSize = 100
        apiGetOutsourcerList(listQuery).then(response => {
          this.outsourceOptions = response.data
        })
      },
      wholeProcessExport () {
        let listQuery = {
          pointId: this.repairDto.pointId,
          pointType: this.repairDto.pointType,
          provinceCode: this.repairDto.provinceCode,
          cityCode: this.repairDto.cityCode,
          acceptBeginTime: this.repairDto.acceptTime[0],
          acceptEndTime: this.repairDto.acceptTime[1],
          ystsn: this.repairDto.ystsn,
          repairBeginTime: this.repairDto.repairTime[0],
          repairEndTime: this.repairDto.repairTime[1],
          startYMD: this.repairDto.startYMD
        }
        this.wholeProcessLoading = true
        apiWholeProcessExcel(listQuery).then(response => {
          let blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
          window.location.href = URL.createObjectURL(blob)
          this.wholeProcessLoading = false
        }).catch(() => {
        })
      }
    },
    watch: {
      'repairDto.repairSite': {
        handler (val, oldVal) {
          this.repairDto.repairResult = ''
          if (val === 1) {
            // factory
            this.resultChart = [
              {value: 2, label: '已修复'},
              {value: 4, label: '待报废'},
              {value: 5, label: '已报废'},
              {value: 6, label: '报废未批准'}
            ]
          } else {
            this.resultChart = [
              {value: 1, label: '待修复'},
              {value: 2, label: '已修复'},
              {value: 3, label: '原物返回'}
            ]
          }
        },
        deep: true,
        immediate: true
      }
    }
  }
</script>
